<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>بازی ماشین‌سواری فانتزی و واژگان</title>
    
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;700;900&display=swap" media="print" onload="this.media='all'">
    
    <style>
        :root {
            --primary: #FF5252;
            --secondary: #448AFF;
            --success: #69F0AE;
            --warning: #FFD740;
            --dark: #2c3e50;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            user-select: none;
            font-family: 'Vazirmatn', sans-serif;
        }

        body {
            background-color: #2E7D32; 
            overflow: hidden;
            touch-action: none;
        }

        #gameCanvas {
            display: block;
            margin: 0 auto;
            box-shadow: 0 0 30px rgba(0,0,0,0.9);
        }

        .hud {
            position: absolute;
            top: 10px;
            width: 100%;
            display: flex;
            justify-content: space-between;
            padding: 0 20px;
            pointer-events: none;
            z-index: 10;
        }

        .hud-box {
            background: rgba(255, 255, 255, 0.95);
            padding: 10px 15px;
            border-radius: 15px;
            border: 2px solid #ccc;
            box-shadow: 0 5px 15px rgba(0,0,0,0.4);
            font-weight: bold;
            color: var(--dark);
            font-size: 14px;
            pointer-events: auto;
        }

        .level-banner {
            position: absolute;
            top: 10px;
            left: 50%;
            transform: translateX(-50%);
            background: linear-gradient(145deg, #FFD740, #FF8F00);
            padding: 8px 25px;
            border-radius: 20px;
            font-size: 20px;
            font-weight: 900;
            color: #fff;
            border: 3px solid #fff;
            box-shadow: 0 5px 15px rgba(0,0,0,0.5);
            z-index: 20;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            transition: transform 0.3s;
        }

        .mute-btn {
            background: #fff;
            border: 2px solid #ccc;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            font-size: 20px;
            cursor: pointer;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3);
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 10px;
        }

        .controls {
            position: absolute;
            bottom: 20px;
            width: 100%;
            display: flex;
            justify-content: space-between; 
            align-items: flex-end;
            padding: 0 20px;
            z-index: 10;
        }

        .btn {
            background: linear-gradient(145deg, #448AFF, #1976D2);
            color: white;
            border: none;
            width: 70px;
            height: 70px;
            border-radius: 50%;
            font-size: 24px;
            font-weight: 900;
            box-shadow: 0 8px 0 #0D47A1, 0 15px 20px rgba(0,0,0,0.5);
            cursor: pointer;
            transition: transform 0.1s, box-shadow 0.1s;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .btn:active {
            transform: translateY(8px);
            box-shadow: 0 0px 0 #0D47A1, 0 5px 10px rgba(0,0,0,0.5);
        }

        .btn-shoot {
            background: linear-gradient(145deg, #FF5252, #D50000);
            box-shadow: 0 8px 0 #B71C1C, 0 15px 20px rgba(0,0,0,0.5);
        }
        
        .btn-shoot:active {
            box-shadow: 0 0px 0 #B71C1C, 0 5px 10px rgba(0,0,0,0.5);
        }

        #questionModal, #startModal, #gameOverModal, #messageModal {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.85);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 100;
        }

        #countdownModal {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 200;
            color: #FFD740;
            text-align: center;
            overflow: hidden;
        }

        #countdownText {
            font-size: 120px;
            font-weight: 900;
            text-shadow: 0 10px 30px rgba(0,0,0,0.8);
            display: block;
        }
        
        #continueText {
            font-size: 30px;
            color: white;
            margin-top: -20px;
            text-shadow: 0 5px 10px rgba(0,0,0,0.8);
        }

        .encouragement {
            font-size: 40px;
            color: #69F0AE;
            text-shadow: 0 5px 15px rgba(0,0,0,0.9);
            margin-bottom: 20px;
            font-weight: 900;
            animation: popIn 0.5s ease-out;
            padding: 0 10px;
        }

        @keyframes popIn {
            0% { transform: scale(0.5); opacity: 0; }
            100% { transform: scale(1); opacity: 1; }
        }

        .modal-content {
            background: #fff;
            padding: 25px;
            border-radius: 20px;
            text-align: center;
            max-width: 95%;
            width: 450px;
            border: 4px solid var(--warning);
            box-shadow: 0 10px 40px rgba(0,0,0,0.7);
        }

        .start-screen-content {
            padding: 20px;
            width: 400px;
        }

        .modal-content h2 { margin-bottom: 15px; color: var(--dark); font-size: 22px;}
        .modal-content input {
            width: 100%;
            padding: 15px;
            font-size: 18px;
            border: 2px solid #ccc;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
            outline: none;
        }
        
        .options-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 10px;
            margin-top: 15px;
        }

        .option-btn {
            background: var(--secondary);
            color: white;
            border: none;
            padding: 14px;
            font-size: 15px;
            font-weight: bold;
            border-radius: 10px;
            cursor: pointer;
            box-shadow: 0 4px 0 #1976D2;
            transition: background 0.2s, transform 0.1s;
            white-space: normal;
            line-height: 1.5;
        }

        .option-btn:active { transform: translateY(4px); box-shadow: none; }
        
        .start-btn {
            background: linear-gradient(145deg, #69F0AE, #00C853);
            color: var(--dark);
            border: none;
            padding: 15px 35px;
            font-size: 18px;
            font-weight: bold;
            border-radius: 15px;
            cursor: pointer;
            box-shadow: 0 6px 0 #009624;
            transition: transform 0.1s, box-shadow 0.1s;
            margin-top: 10px;
            width: 100%;
        }
        
        .start-btn:active {
            transform: translateY(6px);
            box-shadow: 0 0px 0 #009624;
        }

        .continue-btn {
            background: linear-gradient(145deg, #FF9800, #F57C00);
            box-shadow: 0 6px 0 #E65100;
            margin-bottom: 10px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            text-align: right;
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            border: 1px solid #ddd;
            margin-bottom: 15px;
        }
        
        .motivation {
            font-size: 16px;
            color: #1976D2;
            font-weight: bold;
            margin-bottom: 20px;
        }

        .boss-hp-bar {
            position: absolute;
            top: 60px;
            left: 50%;
            transform: translateX(-50%);
            width: 80%;
            height: 20px;
            background: #333;
            border: 2px solid #FFF;
            border-radius: 10px;
            display: none;
            z-index: 10;
        }
        .boss-hp-fill {
            width: 100%;
            height: 100%;
            background: #FF1744;
            border-radius: 8px;
            transition: width 0.2s;
        }

        @keyframes pulse-glow {
            0% {
                box-shadow: 0 0 5px #BBDEFB, 0 0 10px #BBDEFB;
                transform: scale(1);
            }
            50% {
                box-shadow: 0 0 15px #448AFF, 0 0 25px #448AFF;
                transform: scale(1.02);
            }
            100% {
                box-shadow: 0 0 5px #BBDEFB, 0 0 10px #BBDEFB;
                transform: scale(1);
            }
        }

        .start-screen-content a {
            animation: pulse-glow 2.5s infinite ease-in-out;
        }

        .start-icon {
            transition: transform 0.2s ease-out, box-shadow 0.2s ease-out;
        }
        .start-icon:hover {
            transform: scale(1.08) translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.5), inset 0 0 10px rgba(255,255,255,0.3) !important;
        }

        @media print {
            body * { visibility: hidden; }
            #gameOverModal, #gameOverModal * { visibility: visible; }
            #gameOverModal { position: absolute; left: 0; top: 0; background: white !important; display: block; }
            .modal-content { border: none; box-shadow: none; width: 100%; margin: 0 auto; }
            .no-print { display: none !important; }
        }
    </style>
</head>
<body>

    <div class="hud" id="hud" style="display:none;">
        <div style="display: flex; flex-direction: column;">
            <button id="muteBtn" class="mute-btn" onclick="toggleMute()">🔊</button>
            <div class="hud-box">
                ⏱ زمان: <span id="timeDisplay">0</span>s<br>
                🛣 مسافت: <span id="distDisplay">0.0</span> km<br>
                ⚡ سرعت: <span id="speedDisplay">100</span>%
            </div>
        </div>
        <div id="levelDisplay" class="level-banner">سطح ۱</div>
        <div class="hud-box" style="text-align: left;">
            👤 <span id="nameDisplay">بازیکن</span><br>
            ⭐ امتیاز: <span id="scoreDisplay">0</span><br>
            ❤️ جان: <span id="livesDisplay">❤️❤️❤️❤️❤️</span><br>
            🔫 تیر: <span id="ammoDisplay">5</span><br>
            ✅ صحیح: <span id="correctDisplay">0</span>
        </div>
    </div>

    <div class="boss-hp-bar" id="bossHpBar"><div class="boss-hp-fill" id="bossHpFill"></div></div>

    <canvas id="gameCanvas"></canvas>

    <div class="controls" id="controls" style="display:none;">
        <button class="btn" id="btnRight">▶</button>
        <button class="btn btn-shoot" id="btnShoot">💥</button>
        <button class="btn" id="btnLeft">◀</button>
    </div>

    <div id="startModal" style="display:flex;">
        <div class="modal-content start-screen-content">
            <h1 style="color: var(--primary); font-size: 26px; margin-bottom: 10px; text-shadow: 1px 1px 2px rgba(0,0,0,0.2);">🚗 نبرد واژگان در جاده</h1>
            <p style="font-size: 14px; margin-bottom: 15px; color: #444; font-weight: bold;">به بازی آموزشی ما خوش آمدی! ماشینت رو هدایت کن، کلمات رو یاد بگیر و غول‌ها رو شکست بده.</p>
            
            
            <p style="font-size: 13px; font-weight: bold; color: var(--dark); margin-bottom: 15px; line-height: 1.6; background: #f0f0f0; padding: 10px; border-radius: 10px;">
                تهیه‌کننده: احمد عالی پور<br>آموزگار و عضو کارگروه هوش مصنوعی استان چهار محال و بختیاری
            </p>

            </a>
            
            <input type="text" id="playerNameInput" placeholder="نام خودت رو اینجا بنویس...">
            <button class="start-btn" onclick="startGame()">شروع بازی</button>
        </div>
    </div>

    <div id="questionModal">
        <div class="modal-content">
            <h2 id="questionText">معنی این کلمه چیست؟</h2>
            <div class="options-grid" id="optionsContainer"></div>
        </div>
    </div>

    <div id="countdownModal">
        <div>
            <div id="encouragementText" class="encouragement" style="display:none;"></div>
            <span id="countdownText">3</span>
            <div id="continueText">ادامه...</div>
        </div>
    </div>

    <div id="messageModal">
        <div class="modal-content">
            <h2 id="msgBoxText" style="color: #4CAF50; font-size: 26px;"></h2>
        </div>
    </div>

    <div id="gameOverModal">
        <div class="modal-content">
            <h2 id="gameOverTitle">💥 تصادف کردی! کارنامه بازی</h2>
            <div class="stats-grid">
                <div>👤 بازیکن: <span id="finalName"></span></div>
                <div>🏆 سطح: <span id="finalLevel"></span></div>
                <div>⭐ امتیاز: <span id="finalScore"></span></div>
                <div>⏱ زمان: <span id="finalTime"></span>s</div>
                <div>🛣 مسافت: <span id="finalDist"></span> km</div>
                <div>⚡ بیشترین سرعت: <span id="finalSpeed"></span>%</div>
                <div style="grid-column: span 2; text-align: center;">✅ پاسخ صحیح: <span id="finalCorrect"></span></div>
            </div>
            <div class="motivation" id="gameoverMotiv">شکست مقدمه پیروزیه، دفعه بعد حتما رکورد می‌زنی قهرمان! 🌟</div>
            <button class="start-btn continue-btn no-print" id="btnRevive" onclick="revivePlayer()" style="display:none;">ادامه بده (آخرین فرصت)</button>
            <button class="start-btn no-print" onclick="window.print()" style="background: linear-gradient(145deg, #FFD740, #FFC400); box-shadow: 0 6px 0 #FF8F00; margin-bottom:10px;">چاپ کارنامه</button>
            <button class="start-btn no-print" onclick="location.reload()">دوباره بازی کن</button>
        </div>
    </div>

    <script>
        const bgMusic = new Audio('https://dl.sevilmusics.com/cdn/music/srvrs/Non%20Vocal%20Bass%20Music%20_04%20%5BSevilMusic%5D.mp3');
        bgMusic.loop = true; bgMusic.volume = 0.3;
        const shootSoundTemplate = new Audio('https://sedatoseda.com/wp-content/uploads/shotgun-sound.mp3');
        shootSoundTemplate.volume = 0.8;
        const tankAudio = new Audio('https://sedatoseda.com/wp-content/uploads/tank-moving-143104.mp3');
        tankAudio.loop = true; 
        tankAudio.volume = 0.6; 
        const reloadAudio = new Audio('https://dl4.fara-download.ir/audio/sound_effect/objects/guns/reload/gun_reload3.mp3');
        reloadAudio.volume = 0.9;
        const turboAudio = new Audio('https://sedatoseda.com/wp-content/uploads/Turbo-sound-2.mp3');
        turboAudio.volume = 0.8;
        const applauseAudio = new Audio('https://sedatoseda.com/wp-content/uploads/Applause-Sound-2.mp3');
        applauseAudio.volume = 0.8;

        let audioCtx;
        let isMuted = false;

        function initAudio() {
            if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
            if(audioCtx.state === 'suspended') audioCtx.resume();
        }

        function playSfx(type) {
            if (isMuted || !audioCtx) return;
            const osc = audioCtx.createOscillator();
            const gain = audioCtx.createGain();
            osc.connect(gain);
            gain.connect(audioCtx.destination);
            gain.gain.value = 1.0;
            const now = audioCtx.currentTime;

            if (type === 'crash') {
                osc.type = 'sawtooth';
                osc.frequency.setValueAtTime(150, now);
                osc.frequency.exponentialRampToValueAtTime(10, now + 0.5);
                gain.gain.setValueAtTime(1.0, now);
                gain.gain.exponentialRampToValueAtTime(0.01, now + 0.5);
                osc.start(now); osc.stop(now + 0.5);
            } else if (type === 'powerup') {
                osc.type = 'sine';
                osc.frequency.setValueAtTime(400, now);
                osc.frequency.linearRampToValueAtTime(800, now + 0.3);
                gain.gain.setValueAtTime(1.0, now);
                gain.gain.exponentialRampToValueAtTime(0.01, now + 0.3);
                osc.start(now); osc.stop(now + 0.3);
            } else if (type === 'correct') {
                osc.type = 'square';
                osc.frequency.setValueAtTime(400, now);
                osc.frequency.setValueAtTime(600, now + 0.1);
                gain.gain.setValueAtTime(1.0, now);
                gain.gain.exponentialRampToValueAtTime(0.01, now + 0.3);
                osc.start(now); osc.stop(now + 0.3);
            } else if (type === 'wrong') {
                osc.type = 'sawtooth';
                osc.frequency.setValueAtTime(300, now);
                osc.frequency.linearRampToValueAtTime(100, now + 0.4);
                gain.gain.setValueAtTime(1.0, now);
                gain.gain.exponentialRampToValueAtTime(0.01, now + 0.4);
                osc.start(now); osc.stop(now + 0.4);
            } else if (type === 'enemyShoot') {
                osc.type = 'square';
                osc.frequency.setValueAtTime(800, now);
                osc.frequency.exponentialRampToValueAtTime(100, now + 0.2);
                gain.gain.setValueAtTime(0.5, now);
                gain.gain.exponentialRampToValueAtTime(0.01, now + 0.2);
                osc.start(now); osc.stop(now + 0.2);
            }
        }

        function toggleMute() {
            isMuted = !isMuted;
            const btn = document.getElementById('muteBtn');
            if (isMuted) {
                bgMusic.pause(); tankAudio.pause(); turboAudio.pause(); applauseAudio.pause();
                btn.innerText = '🔇';
            } else {
                bgMusic.play().catch(e => console.log(e));
                btn.innerText = '🔊';
            }
        }

        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        
        let width, height, roadWidth;
        let targetLanes = 3;
        let currentLanes = 3;
        let laneWidth;
        let curveDirection = 1;
        let targetCurveMagnitude = 0;
        let currentCurveMagnitude = 0;

        function resize() {
            width = window.innerWidth > 600 ? 600 : window.innerWidth;
            height = window.innerHeight;
            canvas.width = width;
            canvas.height = height;
            roadWidth = width - 30;
            laneWidth = roadWidth / currentLanes;
            player.y = height - 120; 
            player.currentX = 15 + (player.lane * laneWidth) + (laneWidth / 2);
        }
        window.addEventListener('resize', resize);

        function getCurveOffset(y) {
            let relativeY = height - y;
            if (relativeY < 0) relativeY = 0;
            let factor = Math.pow(relativeY / height, 1.5);
            return Math.sin(distance * 0.003 * curveDirection) * factor * (width * currentCurveMagnitude);
        }
        
        let gameLoopId;
        let isPaused = false;
        let frames = 0;
        let score = 0, lives = 5, ammo = 5, distance = 0, time = 0, level = 1; 
        let correctAnswers = 0;
        let playerName = "بازیکن";
        let roadOffset = 0;
        let initialGameSpeed = 5;
        let gameSpeed = initialGameSpeed;
        let maxSpeedReached = 100;
        let difficultyMultiplier = 1;
        let activePowerup = null;
        let hasRevived = false;
        let MAX_LEVEL = 10;
        
        let lastTurboTime = 0;
        let lastRepairTime = 0;
        let lastAmmoTime = 0;
        let lastShieldTime = 0;

        // Boss states
        let isBossMode = false;
        let boss = null;
        let bossBullets = [];
        let bossBasesDestroyed = 0;
        let preBossGameSpeed = 5;

        function getEncouragement() {
            const list = [
                `آفرین قهرمان ${playerName}! 🥇`, 
                `کارت عالی بود ${playerName}! 🌟`, 
                `تو بی‌نظیری ${playerName}! 🚀`, 
                `ایول دانشمند کوچک! 💡`, 
                `فوق‌العاده‌ای ${playerName}! 🤩`
            ];
            return list[Math.floor(Math.random() * list.length)];
        }

        const vocabList = [
            { w: "سلیمان", m: "نام یکی از پیامبران الهی" }, { w: "مهارت", m: "ماهر بودن در کاری" },
            { w: "موری", m: "مورچه ای" }, { w: "حساب کردن", m: "شمردن" },
            { w: "وزان", m: "مخفف و از آن" }, { w: "اختر شناسی", m: "ستاره شناسی ، نجوم" },
            { w: "گران", m: "بزرگ و سنگین" }, { w: "حکمت", m: "دانش و معرفت و علم" },
            { w: "کاه", m: "علف" }, { w: "ناگزیر", m: "ناچار" },
            { w: "سعی", m: "تلاش و کوشش" }, { w: "نان آور خانه", m: "کسی که مایحتاج خانواده را فراهم می‌‌کند" },
            { w: "فارغ", m: "آسوده ، راحت" }, { w: "یاور", m: "یاری کننده" },
            { w: "به تندی", m: "به سرعت" }, { w: "کسب علم و معرفت", m: "به دست آوردن علم و دانش" },
            { w: "مسکین", m: "نیازمند" }, { w: "مهرگان", m: "پاییز ، اوایل پاییز" },
            { w: "ملک", m: "سرزمین، قلمرو" }, { w: "دانستم", m: "فهمیدم، دریافتم" },
            { w: "خونابه خوردن", m: "رنج بسیار کشیدن" }, { w: "عزم", m: "قصد ، اراده" },
            { w: "میازار", m: "آزار نرسان" }, { w: "شدم", m: "رفتم" },
            { w: "سور", m: "جشن و مهمانی" }, { w: "عالمان", m: "دانایان، خردمندان" },
            { w: "قناعت", m: "قانع بودن" }, { w: "مردم عادی", m: "عامه ی مردم" },
            { w: "توشه", m: "خوراک و آذوقه سفر" }, { w: "دیار", m: "سرزمین ، ناحیه" },
            { w: "گنج", m: "گوهر ها و چیزهای قیمتی" }, { w: "پژوهش", m: "تحقیق" },
            { w: "همواره", m: "همیشه" }, { w: "خردمندانه", m: "عاقلانه" },
            { w: "کامکاری", m: "نیک بختی ، خوش بختی" }, { w: "چه بسا", m: "بسیار ، فراوان" },
            { w: "رسم", m: "روش ، شیوه" }, { w: "پرسشگر", m: "سوال کننده" },
            { w: "بردباری", m: "شکیبایی، صبر" }, { w: "هوشمندی", m: "آگاهی" },
            { w: "هشیاران", m: "عاقلان، دانایان" }, { w: "گَه", m: "مخفف گاه" },
            { w: "به سبب", m: "به علت" }, { w: "تدبیر", m: "اندیشیدن به منظور پیدا کردن راه حلی برای مشکل" },
            { w: "پس از درگذشت مادر", m: "پس از فوت مادر" }, { w: "عاقل", m: "دانا ، عالم" },
            { w: "راهزنی", m: "غارتگری" }, { w: "بینا", m: "آگاه و هوشیار" },
            { w: "سکه", m: "پول فلزی" }, { w: "پیرایه", m: "آنچه سبب زیبایی شود، ابزار آراستن، زیور و زینت" },
            { w: "صادق", m: "راستگو" }, { w: "اینک", m: "حالا" },
            { w: "دینار", m: "سکه ی طلا" }, { w: "پیشگاه", m: "صحن" },
            { w: "حضور یافته ام", m: "مشرف شده ام، آمده ام" }, { w: "ناپسند", m: "نکوهیده، زشت" },
            { w: "جایگاه", m: "مرتبه ، درجه" }, { w: "صمیمی", m: "بسیار نزدیک" },
            { w: "رحمت حق بر آنان باد", m: "لطف خدا بر آنان باد" }, { w: "هم نشین", m: "دوست" },
            { w: "شوق آموختن", m: "علاقه به یاد گرفتن" }, { w: "خاکیان", m: "اهل خاک، مردم و انسان ها" },
            { w: "مکتب", m: "مدرسه ، دبستان" }, { w: "برکرده اند", m: "بلند کرده‌اند" },
            { w: "از بر کردم", m: "حفظ کردم" }, { w: "خاکدان", m: "دنیای خاکی، این جهان" },
            { w: "آداب", m: "رسم و روش" }, { w: "ضمیر", m: "باطن" },
            { w: "معین کرد", m: "مشخص کرد" }, { w: "لطف", m: "مهربانی ، رحمت" },
            { w: "پر مهر", m: "پر از عشق و محبت" }, { w: "پرتو", m: "روشنایی" },
            { w: "اثر گذار", m: "تاثیر گذار" }, { w: "معرفت", m: "شناخت و علم" },
            { w: "ماندگار", m: "پایدار، ماندنی" }, { w: "بپرور", m: "پرورش بده" },
            { w: "بدگویی حسودان", m: "بد گفتن و به زشتی یاد کردن انسان‌های حسود" }, { w: "نیک", m: "خوش، خوب" },
            { w: "رانده شده", m: "اخراج شد" }, { w: "خوارزم", m: "نام سرزمینی که ابوریحان در آن زندگی می‌‌کرد" },
            { w: "غافلان", m: "نادانان" }
        ];

        let availableVocabList = [...vocabList];

        function drawCar(ctx, x, y, baseColor, isPlayer = false) {
            ctx.save();
            ctx.translate(x, y);
            ctx.scale(0.6, 0.6); 
            
            ctx.fillStyle = "rgba(0, 0, 0, 0.6)";
            ctx.beginPath();
            ctx.roundRect(-24, -38, 48, 80, 12);
            ctx.fill();

            ctx.fillStyle = "#111";
            ctx.fillRect(-26, -26, 10, 18);
            ctx.fillRect(16, -26, 10, 18);
            ctx.fillRect(-26, 14, 10, 18);
            ctx.fillRect(16, 14, 10, 18);
            
            let carGrad = ctx.createLinearGradient(-20, 0, 20, 0);
            if(baseColor === "#D50000") {
                carGrad.addColorStop(0, "#8E0000");
                carGrad.addColorStop(0.5, "#FF1744");
                carGrad.addColorStop(1, "#8E0000");
            } else {
                carGrad.addColorStop(0, "#01579B");
                carGrad.addColorStop(0.5, "#29B6F6");
                carGrad.addColorStop(1, "#01579B");
            }

            ctx.fillStyle = carGrad;
            ctx.beginPath();
            ctx.roundRect(-20, -36, 40, 72, 12);
            ctx.fill();
            
            if (isPlayer) {
                ctx.fillStyle = "#FFF";
                ctx.fillRect(-4, -34, 8, 68);
            }

            let glassGrad = ctx.createLinearGradient(0, -18, 0, 18);
            glassGrad.addColorStop(0, "#81D4FA");
            glassGrad.addColorStop(1, "#0277BD");
            ctx.fillStyle = glassGrad;
            ctx.beginPath();
            ctx.roundRect(-16, -20, 32, 40, 6);
            ctx.fill();
            
            ctx.fillStyle = carGrad;
            ctx.beginPath();
            ctx.roundRect(-14, -10, 28, 20, 4);
            ctx.fill();

            ctx.fillStyle = "#FFF59D";
            ctx.shadowColor = "#FFF59D";
            ctx.shadowBlur = 15;
            ctx.beginPath();
            ctx.roundRect(-16, -35, 8, 5, 2);
            ctx.roundRect(8, -35, 8, 5, 2);
            ctx.fill();
            ctx.shadowBlur = 0; 
            
            ctx.fillStyle = "#FF1744";
            ctx.beginPath();
            ctx.roundRect(-16, 32, 8, 4, 1);
            ctx.roundRect(8, 32, 8, 4, 1);
            ctx.fill();
            ctx.restore();
        }

        function drawTank(ctx, x, y, hp, scale = 0.6) {
            ctx.save();
            ctx.translate(x, y);
            ctx.rotate(Math.PI); 
            ctx.scale(scale, scale);
            
            ctx.fillStyle = "rgba(0, 0, 0, 0.6)";
            ctx.fillRect(-40, -50, 80, 100);

            ctx.fillStyle = "#111";
            ctx.fillRect(-38, -52, 18, 104);
            ctx.fillRect(20, -52, 18, 104);
            ctx.fillStyle = "#555";
            for(let i = -50; i < 50; i += 10) {
                ctx.fillRect(-38, i, 18, 4);
                ctx.fillRect(20, i, 18, 4);
            }
            
            let tankGrad = ctx.createLinearGradient(-25, 0, 25, 0);
            tankGrad.addColorStop(0, "#2E3B32");
            tankGrad.addColorStop(0.5, "#4CAF50");
            tankGrad.addColorStop(1, "#2E3B32");
            ctx.fillStyle = tankGrad; 
            ctx.beginPath();
            ctx.roundRect(-25, -45, 50, 90, 8);
            ctx.fill();
            
            let barrelGrad = ctx.createLinearGradient(-8, 0, 8, 0);
            barrelGrad.addColorStop(0, "#1B5E20");
            barrelGrad.addColorStop(1, "#0A210C");
            ctx.fillStyle = barrelGrad;
            ctx.fillRect(-8, -75, 16, 50);
            ctx.fillStyle = "#000";
            ctx.fillRect(-10, -80, 20, 6);
            
            ctx.fillStyle = tankGrad;
            ctx.shadowColor = "rgba(0,0,0,0.6)";
            ctx.shadowOffsetY = 5;
            ctx.shadowBlur = 10;
            ctx.beginPath();
            ctx.arc(0, 5, 25, 0, Math.PI * 2);
            ctx.fill();
            ctx.shadowBlur = 0;
            ctx.shadowOffsetY = 0;

            // FIX: Only show damage indicator for the boss (which has a larger scale)
            if(hp <= 5 && scale > 1) {
                ctx.fillStyle = "rgba(255, 60, 0, 0.5)";
                ctx.beginPath();
                ctx.arc(0, 5, 25, 0, Math.PI * 2);
                ctx.fill();
            }
            ctx.restore();
        }

        function drawPowerupIcon(ctx, x, y, type) {
            ctx.save();
            ctx.translate(x, y);
            ctx.scale(0.75, 0.75); 
            
            ctx.beginPath();
            ctx.arc(0, 0, 22, 0, Math.PI*2);
            
            if(type === 'repair') {
                ctx.fillStyle = "rgba(255, 20, 147, 0.3)";
                ctx.shadowColor = "#FF1493";
                ctx.shadowBlur = 15;
                ctx.fill();
                ctx.shadowBlur = 0;
                ctx.fillStyle = "#FF1493";
                ctx.beginPath();
                ctx.moveTo(0, 8);
                ctx.bezierCurveTo(-10, -2, -20, -8, -10, -15);
                ctx.bezierCurveTo(-2, -20, 0, -10, 0, -10);
                ctx.bezierCurveTo(0, -10, 2, -20, 10, -15);
                ctx.bezierCurveTo(20, -8, 10, -2, 0, 8);
                ctx.fill();
            } 
            else if(type === 'ammo') {
                ctx.fillStyle = "rgba(0, 229, 255, 0.3)";
                ctx.shadowColor = "#00E5FF";
                ctx.shadowBlur = 15;
                ctx.fill();
                ctx.shadowBlur = 0;
                ctx.fillStyle = "#00E5FF";
                ctx.beginPath();
                ctx.roundRect(-6, -10, 12, 18, 2);
                ctx.fill();
                ctx.fillStyle = "#00B0FF";
                ctx.beginPath();
                ctx.moveTo(-6, -10);
                ctx.lineTo(0, -16);
                ctx.lineTo(6, -10);
                ctx.fill();
            }
            else if(type === 'turbo') {
                ctx.fillStyle = "rgba(255, 234, 0, 0.3)";
                ctx.shadowColor = "#FFEA00";
                ctx.shadowBlur = 15;
                ctx.fill();
                ctx.shadowBlur = 0;
                ctx.fillStyle = "#FFEA00";
                ctx.beginPath();
                ctx.moveTo(4, -14);
                ctx.lineTo(-10, 2);
                ctx.lineTo(0, 2);
                ctx.lineTo(-4, 14);
                ctx.lineTo(10, -2);
                ctx.lineTo(0, -2);
                ctx.closePath();
                ctx.fill();
            }
            else if(type === 'shield') {
                ctx.fillStyle = "rgba(255, 193, 7, 0.3)";
                ctx.shadowColor = "#FFC107";
                ctx.shadowBlur = 15;
                ctx.fill();
                ctx.shadowBlur = 0;
                ctx.fillStyle = "#FFC107";
                ctx.beginPath();
                ctx.moveTo(0, -15);
                ctx.lineTo(12, -8);
                ctx.lineTo(12, 5);
                ctx.lineTo(0, 15);
                ctx.lineTo(-12, 5);
                ctx.lineTo(-12, -8);
                ctx.closePath();
                ctx.fill();
                ctx.fillStyle = "#FF8F00";
                ctx.beginPath();
                ctx.moveTo(0, -10);
                ctx.lineTo(8, -5);
                ctx.lineTo(8, 3);
                ctx.lineTo(0, 10);
                ctx.lineTo(-8, 3);
                ctx.lineTo(-8, -5);
                ctx.closePath();
                ctx.fill();
            }
            ctx.restore();
        }

        const player = {
            lane: 1, 
            currentX: 0,
            y: 0, 
            turboTimer: 0,
            shieldTimer: 0,
            draw() {
                let targetX = 15 + (this.lane * laneWidth) + (laneWidth / 2);
                this.currentX += (targetX - this.currentX) * 0.2;
                let finalX = this.currentX + getCurveOffset(this.y);

                drawCar(ctx, finalX, this.y, "#D50000", true); 
                
                if(this.turboTimer > 0) {
                    ctx.fillStyle = "#00E5FF";
                    ctx.shadowColor = "#00E5FF";
                    ctx.shadowBlur = 15;
                    ctx.beginPath();
                    ctx.arc(finalX - 8, this.y + 30, 4 + Math.random()*3, 0, Math.PI*2);
                    ctx.arc(finalX + 8, this.y + 30, 4 + Math.random()*3, 0, Math.PI*2);
                    ctx.fill();
                    ctx.shadowBlur = 0;
                }

                if(this.shieldTimer > 0) {
                    ctx.strokeStyle = "rgba(255, 215, 0, 0.9)"; 
                    ctx.lineWidth = 4;
                    ctx.beginPath();
                    ctx.ellipse(finalX, this.y, 35, 55, 0, 0, Math.PI * 2);
                    ctx.stroke();
                    ctx.fillStyle = "rgba(255, 215, 0, 0.2)";
                    ctx.fill();
                }
            }
        };

        resize();

        let enemies = [];
        let bullets = [];
        let powerups = [];

        function startGame() {
            initAudio();
            if (!isMuted) bgMusic.play().catch(e => console.log(e));
            
            let nameInput = document.getElementById('playerNameInput').value.trim();
            if(nameInput !== "") playerName = nameInput;
            document.getElementById('nameDisplay').innerText = playerName;
            document.getElementById('startModal').style.display = 'none';
            document.getElementById('hud').style.display = 'flex';
            document.getElementById('levelDisplay').style.display = 'block';
            document.getElementById('controls').style.display = 'flex';
            
            setInterval(() => { 
                if(!isPaused) {
                    time++; 
                    
                    if (time > 0 && time % 30 === 0 && level < MAX_LEVEL) {
                        level++;
                        gameSpeed *= 1.05; 
                        difficultyMultiplier += 0.2;
                        let banner = document.getElementById('levelDisplay');
                        banner.innerText = "سطح " + level;
                        banner.style.transform = "translateX(-50%) scale(1.3)";
                        setTimeout(() => banner.style.transform = "translateX(-50%) scale(1)", 500);

                        if (level === 3 || level === 6 || level === MAX_LEVEL) {
                            startBossMode();
                        }
                    }
                    
                    if (!isBossMode) {
                        let cycleTime = time % 60;
                        if (cycleTime === 0) {
                            targetCurveMagnitude = 0;
                            targetLanes = 3;
                        } else if (cycleTime === 40) {
                            targetLanes = [2, 3, 4][Math.floor(Math.random() * 3)];
                            curveDirection = (Math.random() > 0.5 ? 1 : -1);
                            targetCurveMagnitude = 0.3 + Math.random() * 0.4;
                        }
                    }
                }
            }, 1000);
            loop();
        }

        function startBossMode() {
            isBossMode = true;
            preBossGameSpeed = gameSpeed;
            targetLanes = 5;
            targetCurveMagnitude = 0;
            boss = {
                hp: 20,
                maxHp: 20,
                y: -150,
                xOffset: 0,
                direction: 1,
                lastShot5: time,
                lastShot10: time
            };
            document.getElementById('bossHpBar').style.display = 'block';
            document.getElementById('bossHpFill').style.width = '100%';
            
            enemies = []; 
            if(!isMuted && tankAudio.paused) tankAudio.play().catch(e=>console.log(e));
        }

        function showVictoryScreen() {
            isPaused = true;
            bgMusic.pause(); tankAudio.pause(); turboAudio.pause();
            
            document.getElementById('gameOverTitle').innerText = "🎉 برنده شدی! کارنامه بازی";
            document.getElementById('finalName').innerText = playerName;
            document.getElementById('finalLevel').innerText = level;
            document.getElementById('finalScore').innerText = score;
            document.getElementById('finalTime').innerText = time;
            document.getElementById('finalDist').innerText = (distance / 100).toFixed(1);
            document.getElementById('finalSpeed').innerText = maxSpeedReached;
            document.getElementById('finalCorrect').innerText = correctAnswers;
            
            document.getElementById('btnRevive').style.display = 'none';
            document.getElementById('gameoverMotiv').innerText = `تو یک قهرمان واقعی هستی ${playerName}! 🌟 تمام پایگاه‌های دشمن نابود شدند.`;
            
            generateConfetti(); 
            document.getElementById('gameOverModal').style.display = 'flex';
        }

        function loop() {
            if (!isPaused) {
                update();
                draw();
            }
            gameLoopId = requestAnimationFrame(loop);
        }

        function update() {
            frames++;
            
            currentLanes += (targetLanes - currentLanes) * 0.02;
            currentCurveMagnitude += (targetCurveMagnitude - currentCurveMagnitude) * 0.02;
            laneWidth = roadWidth / currentLanes;

            let maxLaneIndex = Math.round(currentLanes) - 1;
            if (player.lane > maxLaneIndex) player.lane = maxLaneIndex;
            enemies.forEach(e => { if (e.lane > maxLaneIndex) e.lane = maxLaneIndex; });
            powerups.forEach(p => { if (p.lane > maxLaneIndex) p.lane = maxLaneIndex; });

            if (isBossMode) {
                gameSpeed -= 0.05; 
                if (gameSpeed < 3) gameSpeed = 3;
            }

            // تغییر سرعت توربو به 1.5 برابر
            let speedMultiplier = player.turboTimer > 0 ? 1.5 : 1;
            let currentSpeed = gameSpeed * speedMultiplier;

            let currentSpeedPerc = Math.floor((gameSpeed / initialGameSpeed) * 100);
            if(currentSpeedPerc > maxSpeedReached) maxSpeedReached = currentSpeedPerc;

            distance += (currentSpeed / 10);
            
            if (player.turboTimer > 0) {
                player.turboTimer--;
                if (player.turboTimer === 0) {
                    turboAudio.pause();
                    turboAudio.currentTime = 0;
                }
            }

            if (player.shieldTimer > 0) player.shieldTimer--;

            roadOffset += currentSpeed;
            if (roadOffset > 150) roadOffset = 0;

            let occupiedLanes = powerups.filter(p => p.y < 200).map(p => p.lane);
            let availableLanes = Array.from({length: Math.round(currentLanes)}, (_, i) => i).filter(l => !occupiedLanes.includes(l));

            if (time > 0) {
                // سپر: هر 15 ثانیه
                if (time % 15 === 0 && time !== lastShieldTime) {
                    lastShieldTime = time;
                    if (availableLanes.length > 0) {
                        let lane = availableLanes.splice(Math.floor(Math.random() * availableLanes.length), 1)[0];
                        powerups.push({ lane: lane, y: -250, type: 'shield' });
                    }
                }

                // قلب (تعمیر): هر 5 ثانیه
                if (time % 5 === 0 && time !== lastRepairTime) {
                    lastRepairTime = time;
                    if (availableLanes.length > 0) {
                        let lane = availableLanes.splice(Math.floor(Math.random() * availableLanes.length), 1)[0];
                        powerups.push({ lane: lane, y: -250, type: 'repair' });
                    }
                }

                // توربو: هر 10 ثانیه، فقط در حالت عادی و پس از گذشت 120 ثانیه (دو دقیقه)
                if (time > 120 && time % 10 === 0 && time !== lastTurboTime && !isBossMode) {
                    lastTurboTime = time;
                    if (availableLanes.length > 0) {
                        let lane = availableLanes.splice(Math.floor(Math.random() * availableLanes.length), 1)[0];
                        powerups.push({ lane: lane, y: -250, type: 'turbo' });
                    }
                }

                // خشاب: هر 5 ثانیه در تمام مراحل
                if (time % 5 === 0 && time !== lastAmmoTime) {
                    lastAmmoTime = time;
                    if (availableLanes.length > 0) {
                        let lane = availableLanes.splice(Math.floor(Math.random() * availableLanes.length), 1)[0];
                        powerups.push({ lane: lane, y: -250, type: 'ammo' });
                    }
                }
            }

            if (!isBossMode && frames % Math.max(30, Math.floor(80 - difficultyMultiplier*10)) === 0) {
                let isTank = Math.random() > 0.8 && difficultyMultiplier > 1.2;
                let safeLanes = Array.from({length: Math.round(currentLanes)}, (_, i) => i);
                
                if (!isTank) {
                    let tankLanes = enemies.filter(e => e.type === 'tank').map(e => e.lane);
                    safeLanes = safeLanes.filter(l => !tankLanes.includes(l));
                }

                let occupiedLanesNearTop = enemies.filter(e => e.y > -250 && e.y < 100).map(e => e.lane);
                let uniqueOccupied = [...new Set(occupiedLanesNearTop)];
                
                if (uniqueOccupied.length < Math.round(currentLanes) - 1) {
                    safeLanes = safeLanes.filter(l => !occupiedLanesNearTop.includes(l));
                    if (safeLanes.length > 0) {
                        let lane = safeLanes[Math.floor(Math.random() * safeLanes.length)];
                        enemies.push({ 
                            lane: lane, y: -250, 
                            type: isTank ? 'tank' : 'car', 
                            speed: isTank ? gameSpeed * 0.6 : gameSpeed * 0.9,
                            hp: 1
                        });
                    }
                }
            }

            bullets.forEach((b, index) => {
                b.y -= 15;
                if (b.y < -50) bullets.splice(index, 1);
            });

            let playerLogicalX = player.currentX;

            if (isBossMode && boss) {
                boss.y += (150 - boss.y) * 0.05; 
                
                boss.xOffset += boss.direction * 1.5;
                if (Math.abs(boss.xOffset) > laneWidth * 1.5) boss.direction *= -1;

                let bossX = width / 2 + boss.xOffset;
                
                // شلیک هدف‌دار به سمت بازیکن (هر 5 ثانیه)
                if (time - boss.lastShot5 >= 5) {
                    boss.lastShot5 = time;
                    playSfx('enemyShoot');
                    
                    let dx = playerLogicalX - bossX;
                    let dy = player.y - (boss.y + 60);
                    let dist = Math.hypot(dx, dy) || 1;
                    let speed = 6;
                    bossBullets.push({ x: bossX, y: boss.y + 60, vx: (dx/dist)*speed, vy: (dy/dist)*speed });
                }

                // شلیک پخش (4 تیر جذاب‌تر هر 10 ثانیه)
                if (time - boss.lastShot10 >= 10) {
                    boss.lastShot10 = time;
                    playSfx('enemyShoot');
                    const vxValues = [-2, -0.6, 0.6, 2];
                    vxValues.forEach(vx => {
                        bossBullets.push({ x: bossX, y: boss.y + 60, vx: vx * 1.5, vy: 5 });
                    });
                }

                bullets.forEach((b, bIndex) => {
                    let bLogicalX = 15 + (b.lane * laneWidth) + (laneWidth / 2);
                    if (b.y < boss.y + 80 && Math.abs(bLogicalX - bossX) < 100) {
                        boss.hp--;
                        bullets.splice(bIndex, 1);
                        document.getElementById('bossHpFill').style.width = (boss.hp / boss.maxHp * 100) + '%';
                        if(boss.hp <= 0) {
                            playSfx('crash');
                            isBossMode = false;
                            score += 100;
                            bossBasesDestroyed++;
                            document.getElementById('bossHpBar').style.display = 'none';
                            gameSpeed = preBossGameSpeed;
                            bossBullets = [];
                            
                            isPaused = true;
                            let msg = "";
                            if (level === MAX_LEVEL) {
                                msg = `تبریک ${playerName}! تمام پایگاه‌های دشمن نابود شدند و بازی را بردی!`;
                                document.getElementById('msgBoxText').innerText = msg;
                                document.getElementById('messageModal').style.display = 'flex';
                                setTimeout(() => {
                                    document.getElementById('messageModal').style.display = 'none';
                                    showVictoryScreen(); 
                                }, 4000);
                            } else {
                                let left = 3 - bossBasesDestroyed;
                                msg = bossBasesDestroyed === 1 ? "اولین پایگاه دشمن نابود شد، دو تای دیگه مونده!" : "یک پایگاه دیگر نابود شد!";
                                document.getElementById('msgBoxText').innerText = msg;
                                document.getElementById('messageModal').style.display = 'flex';
                                setTimeout(() => {
                                    document.getElementById('messageModal').style.display = 'none';
                                    isPaused = false;
                                }, 4000);
                            }
                        }
                    }
                });
            }

            bossBullets.forEach((bb, bbIndex) => {
                bb.x += bb.vx;
                bb.y += bb.vy + (speedMultiplier === 1.5 ? gameSpeed*0.5 : 0);
                if (bb.y > height + 50) {
                    bossBullets.splice(bbIndex, 1);
                } else {
                    if (Math.abs(bb.y - player.y) < 40 && Math.abs(bb.x - playerLogicalX) < 30) {
                        bossBullets.splice(bbIndex, 1);
                        if (player.shieldTimer > 0) {
                            playSfx('crash');
                        } else {
                            loseLife();
                        }
                    }
                }
            });

            enemies.forEach((e, eIndex) => {
                e.y += e.speed + (speedMultiplier === 1.5 ? gameSpeed : 0);
                let eLogicalX = 15 + (e.lane * laneWidth) + (laneWidth / 2);
                
                bullets.forEach((b, bIndex) => {
                    let bLogicalX = 15 + (b.lane * laneWidth) + (laneWidth / 2);
                    if (Math.abs(bLogicalX - eLogicalX) < 40 && Math.abs(b.y - e.y) < 30) {
                        e.hp--;
                        bullets.splice(bIndex, 1);
                        if(e.hp <= 0) {
                            playSfx('crash');
                            enemies.splice(eIndex, 1);
                            score += (e.type === 'tank' ? 20 : 10);
                        }
                    }
                });

                if (Math.abs(e.y - player.y) < 65 && Math.abs(eLogicalX - playerLogicalX) < 45) {
                    if (player.shieldTimer > 0) {
                        playSfx('crash');
                        enemies.splice(eIndex, 1);
                        score += (e.type === 'tank' ? 20 : 10);
                    } else {
                        enemies.splice(eIndex, 1);
                        loseLife();
                    }
                }

                if (e.y > height + 50) enemies.splice(eIndex, 1);
            });

            powerups.forEach((p, pIndex) => {
                p.y += currentSpeed * 0.8;
                let pLogicalX = 15 + (p.lane * laneWidth) + (laneWidth / 2);
                if (Math.abs(p.y - player.y) < 60 && Math.abs(pLogicalX - playerLogicalX) < 45) {
                    playSfx('powerup');
                    powerups.splice(pIndex, 1);
                    
                    if (p.type === 'turbo') {
                        player.turboTimer = 300; 
                        if (!isMuted) { turboAudio.currentTime = 0; turboAudio.play().catch(e=>console.log(e)); }
                    } else if (p.type === 'shield') {
                        player.shieldTimer = 300; 
                    } else {
                        activePowerup = p.type;
                        triggerTrivia();
                    }
                }
                if (p.y > height + 50) powerups.splice(pIndex, 1);
            });

            updateHUD();
        }

        function draw() {
            ctx.fillStyle = "#388E3C";
            ctx.fillRect(0, 0, width, height);
            
            ctx.fillStyle = "#2a2a2a";
            ctx.beginPath();
            for(let y = height + 50; y >= -250; y -= 40) {
                ctx.lineTo(15 + getCurveOffset(y), y);
            }
            for(let y = -250; y <= height + 50; y += 40) {
                ctx.lineTo(width - 15 + getCurveOffset(y), y);
            }
            ctx.fill();

            ctx.fillStyle = "rgba(0, 0, 0, 0.2)";
            for(let i = -100; i < height + 100; i += 40) {
                let y = i + (roadOffset % 40);
                let nextY = y + 10;
                let dx1 = getCurveOffset(y);
                let dx2 = getCurveOffset(nextY);
                
                ctx.beginPath();
                ctx.lineTo(15 + dx1, y);
                ctx.lineTo(width - 15 + dx1, y);
                ctx.lineTo(width - 15 + dx2, nextY);
                ctx.lineTo(15 + dx2, nextY);
                ctx.fill();
            }

            ctx.strokeStyle = "#FBC02D";
            ctx.lineWidth = 5;
            ctx.beginPath();
            for(let y = -250; y <= height + 50; y += 40) ctx.lineTo(17 + getCurveOffset(y), y);
            ctx.stroke();
            ctx.beginPath();
            for(let y = -250; y <= height + 50; y += 40) ctx.lineTo(width - 17 + getCurveOffset(y), y);
            ctx.stroke();

            ctx.lineWidth = 6;
            ctx.setLineDash([80, 100]);
            ctx.lineDashOffset = -roadOffset;
            for(let i = 1; i < Math.ceil(currentLanes); i++) {
                let xPos = 15 + (i * laneWidth);
                let opacity = 0.35;
                if (i > currentLanes - 1) {
                    opacity = 0.35 * (currentLanes % 1);
                    if (opacity === 0 && currentLanes % 1 !== 0) opacity = 0.35; 
                }
                ctx.strokeStyle = `rgba(255, 255, 255, ${opacity})`;
                ctx.beginPath();
                for(let y = -250; y <= height + 50; y += 40) {
                    ctx.lineTo(xPos + getCurveOffset(y), y);
                }
                ctx.stroke();
            }
            ctx.setLineDash([]);
            ctx.lineDashOffset = 0;

            if (isBossMode && boss) {
                drawTank(ctx, width / 2 + boss.xOffset + getCurveOffset(boss.y), boss.y, boss.hp, 1.2);
            }

            // طراحی جذاب‌تر و بزرگ‌تر تیرهای تانک
            bossBullets.forEach(bb => {
                let bx = bb.x + getCurveOffset(bb.y);
                let by = bb.y;
                
                ctx.shadowColor = "#FF1744";
                ctx.shadowBlur = 15;
                ctx.fillStyle = "#FF1744";
                ctx.beginPath();
                ctx.arc(bx, by, 10, 0, Math.PI*2);
                ctx.fill();
                ctx.shadowBlur = 0;
                
                ctx.fillStyle = "#FFF";
                ctx.beginPath();
                ctx.arc(bx, by, 4, 0, Math.PI*2);
                ctx.fill();
            });

            bullets.forEach(b => {
                let bx = 15 + (b.lane * laneWidth) + (laneWidth/2) + getCurveOffset(b.y);
                ctx.fillStyle = "#FF9800";
                ctx.beginPath();
                ctx.roundRect(bx - 3, b.y + 6, 6, 14, 3);
                ctx.fill();
                ctx.fillStyle = "#FFF";
                ctx.shadowColor = "#FFFF00";
                ctx.shadowBlur = 10;
                ctx.beginPath();
                ctx.roundRect(bx - 4, b.y - 10, 8, 20, 4);
                ctx.fill();
                ctx.shadowBlur = 0;
            });

            powerups.forEach(p => {
                let x = 15 + (p.lane * laneWidth) + (laneWidth/2) + getCurveOffset(p.y);
                drawPowerupIcon(ctx, x, p.y, p.type);
            });

            enemies.forEach(e => {
                let x = 15 + (e.lane * laneWidth) + (laneWidth/2) + getCurveOffset(e.y);
                if(e.type === 'tank') drawTank(ctx, x, e.y, e.hp);
                else drawCar(ctx, x, e.y, "#1976D2");
            });

            player.draw();
        }

        document.getElementById('btnRight').addEventListener('touchstart', (e) => { e.preventDefault(); moveRight(); });
        document.getElementById('btnRight').addEventListener('mousedown', moveRight);

        document.getElementById('btnLeft').addEventListener('touchstart', (e) => { e.preventDefault(); moveLeft(); });
        document.getElementById('btnLeft').addEventListener('mousedown', moveLeft);
        
        function moveRight() { if(player.lane < Math.round(currentLanes) - 1) player.lane++; }
        function moveLeft() { if(player.lane > 0) player.lane--; }

        document.getElementById('btnShoot').addEventListener('touchstart', (e) => { e.preventDefault(); shoot(); });
        document.getElementById('btnShoot').addEventListener('mousedown', shoot);

        function shoot() {
            if (ammo > 0) {
                if (!isMuted) {
                    let shootSnd = shootSoundTemplate.cloneNode();
                    shootSnd.volume = 0.8;
                    shootSnd.play().catch(e=>console.log(e));
                }
                bullets.push({ lane: player.lane, y: player.y - 25 });
                ammo--;
                updateHUD();
            }
        }

        function loseLife() {
            playSfx('crash');
            lives--;
            if (lives <= 0) {
                isPaused = true;
                bgMusic.pause(); tankAudio.pause(); turboAudio.pause();
                
                document.getElementById('gameOverTitle').innerText = "💥 تصادف کردی! کارنامه بازی";
                document.getElementById('finalName').innerText = playerName;
                document.getElementById('finalLevel').innerText = level;
                document.getElementById('finalScore').innerText = score;
                document.getElementById('finalTime').innerText = time;
                document.getElementById('finalDist').innerText = (distance / 100).toFixed(1);
                document.getElementById('finalSpeed').innerText = maxSpeedReached;
                document.getElementById('finalCorrect').innerText = correctAnswers;
                
                if (!hasRevived) {
                    document.getElementById('btnRevive').style.display = 'inline-block';
                    document.getElementById('gameoverMotiv').innerText = `شکست مقدمه پیروزیه، دفعه بعد حتما رکورد می‌زنی قهرمان ${playerName}! 🌟`;
                } else {
                    document.getElementById('btnRevive').style.display = 'none';
                    document.getElementById('gameoverMotiv').innerText = `تلاشت عالی بود ${playerName}! دفعه بعد حتما برنده میشی.`;
                }

                document.getElementById('gameOverModal').style.display = 'flex';
            }
        }

        function revivePlayer() {
            hasRevived = true;
            lives = 3;
            ammo += 5;
            isPaused = false;
            document.getElementById('gameOverModal').style.display = 'none';
            if (!isMuted) bgMusic.play().catch(e => console.log(e));
            enemies = enemies.filter(e => e.y < player.y - 200);
            bossBullets = [];
        }

        function updateHUD() {
            document.getElementById('timeDisplay').innerText = time;
            document.getElementById('distDisplay').innerText = (distance / 100).toFixed(1);
            document.getElementById('speedDisplay').innerText = Math.floor((gameSpeed / initialGameSpeed) * 100);
            document.getElementById('scoreDisplay').innerText = score;
            document.getElementById('ammoDisplay').innerText = ammo;
            document.getElementById('livesDisplay').innerText = "❤️".repeat(lives);
            document.getElementById('correctDisplay').innerText = correctAnswers;
        }

        let currentWord = null;
        
        function triggerTrivia() {
            isPaused = true;
            if (!tankAudio.paused) tankAudio.pause();
            if (!turboAudio.paused) turboAudio.pause(); // توقف صدای توربو
            
            if (availableVocabList.length === 0) {
                availableVocabList = [...vocabList]; 
            }
            
            let randomIndex = Math.floor(Math.random() * availableVocabList.length);
            currentWord = availableVocabList.splice(randomIndex, 1)[0];
            
            let distractors = [];
            while(distractors.length < 3) {
                let randItem = vocabList[Math.floor(Math.random() * vocabList.length)];
                if(randItem.w !== currentWord.w && !distractors.find(d => d.m === randItem.m)) {
                    distractors.push(randItem);
                }
            }
            
            let allOptions = [currentWord, ...distractors];
            allOptions.sort(() => Math.random() - 0.5);

            document.getElementById('questionText').innerText = `معنی واژه «${currentWord.w}» چیست؟`;
            
            const optionsContainer = document.getElementById('optionsContainer');
            optionsContainer.innerHTML = '';
            
            allOptions.forEach(opt => {
                let btn = document.createElement('button');
                btn.className = 'option-btn';
                btn.innerText = opt.m;
                btn.onclick = () => checkAnswer(opt.m === currentWord.m);
                optionsContainer.appendChild(btn);
            });

            document.getElementById('questionModal').style.display = 'flex';
        }

        function generateConfetti() {
            const colors = ['#FF5252', '#448AFF', '#69F0AE', '#FFD740', '#E040FB'];
            const container = document.getElementById('countdownModal');
            for (let i = 0; i < 70; i++) {
                let conf = document.createElement('div');
                conf.className = 'confetti';
                conf.style.left = (40 + Math.random() * 20) + 'vw';
                conf.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
                let tx = (Math.random() - 0.5) * 600 + 'px';
                let ty = -(Math.random() * 600 + 400) + 'px';
                conf.style.setProperty('--tx', tx);
                conf.style.setProperty('--ty', ty);
                conf.style.animation = `shootUp ${Math.random() * 1.5 + 1.5}s ease-out forwards`;
                container.appendChild(conf);
                setTimeout(() => conf.remove(), 3000);
            }
        }

        function checkAnswer(isCorrect) {
            let encText = document.getElementById('encouragementText');
            if (isCorrect) {
                correctAnswers++;
                playSfx('correct');
                
                if (!isMuted) {
                    applauseAudio.currentTime = 0;
                    applauseAudio.play().catch(e=>console.log(e));
                    setTimeout(() => { applauseAudio.pause(); }, 3000);
                }

                encText.innerText = getEncouragement();
                encText.style.display = 'block';
                generateConfetti();

                if (activePowerup === 'ammo') {
                    ammo += 5;
                    if (!isMuted) { reloadAudio.currentTime = 0; reloadAudio.play().catch(e=>console.log(e)); }
                }
                if (activePowerup === 'repair' && lives < 5) lives++;
                
            } else {
                encText.style.display = 'none';
                playSfx('wrong');
                alert("پاسخ اشتباه بود! معنی صحیح: " + currentWord.m);
            }
            
            startCountdown(isCorrect);
        }

        function startCountdown(showEncouragement) {
            document.getElementById('questionModal').style.display = 'none';
            let cdModal = document.getElementById('countdownModal');
            let cdText = document.getElementById('countdownText');
            if (!showEncouragement) document.getElementById('encouragementText').style.display = 'none';
            cdModal.style.display = 'flex';
            
            let count = 3;
            cdText.innerText = count;
            
            let interval = setInterval(() => {
                count--;
                if (count > 0) {
                    cdText.innerText = count;
                } else {
                    clearInterval(interval);
                    cdModal.style.display = 'none';
                    document.getElementById('encouragementText').style.display = 'none';
                    
                    if (!isMuted && player.turboTimer > 0) {
                        turboAudio.play().catch(e=>console.log(e)); // ادامه پخش صدای توربو
                    }
                    isPaused = false; 
                }
            }, 1000);
        }

    </script>
</body>
</html>
